package analyse

import (
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/model/paylog"
	"sg-backend/utils"
	"strconv"
	"time"
)

/**
 * 获取指标卡数据，年度总收入，年度总支出，欠别人的钱，借出去的钱
 * 获取小计数据，本周收入，支出合计，本月收入支出合计
 * path: /api/analyse/totalData
 */
type topCard struct {
	TotalIncome  float64 `json:"totalIncome"`
	TotalPayment float64 `json:"totalPayment"`
	TotalOwe     float64 `json:"totalOwe"`
	TotalLend    float64 `json:"totalLend"`
}
type thisWeek struct {
	TotalIncome  float64 `json:"totalIncome"`
	TotalPayment float64 `json:"totalPayment"`
}
type thisMonth struct {
	TotalIncome  float64 `json:"totalIncome"`
	TotalPayment float64 `json:"totalPayment"`
}

type _totalType struct {
	TopCard   topCard   `json:"topCard"`
	ThisWeek  thisWeek  `json:"thisWeek"`
	ThisMonth thisMonth `json:"thisMonth"`
}

func GetTotalData(ctx *fiber.Ctx) error {

	// 获取年份，按年份选择
	year := ctx.QueryInt("year", time.Now().Year())
	nexYear := year + 1

	// 拼接开始和结束日期
	startDate := strconv.Itoa(year) + "-01-01 00:00:00"
	endDate := strconv.Itoa(nexYear) + "-01-01 00:00:00"

	// 获取本周开始结束日期
	weekStart, weekEnd := utils.WeekIntervalTime(0)

	// 获取本月开始结束日期
	monthStart, monthEnd := utils.MonthIntervalTime(0)

	// 整合返回数据结构
	var data _totalType

	// 1，汇总年度收入
	var IncomeData []paylog.IncomeLog
	if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
		Where("time >= ? AND time < ?", startDate, endDate).
		Find(&IncomeData); err.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "汇总年度收入出错！" + err.Error.Error(),
		})
	}
	total := float64(0)
	for _, v := range IncomeData {
		total = total + v.Money
	}

	// 年度收入汇总完成
	total = utils.NumberToStr(total)
	data.TopCard.TotalIncome = total

	// 2，汇总年度支出
	var paymentData []paylog.PayLog
	if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
		Where("time >= ? AND time < ?", startDate, endDate).
		Find(&paymentData); err.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "汇总年度支出出错！" + err.Error.Error(),
		})
	}

	// 总数重置为0
	total = float64(0)
	for _, v := range paymentData {
		total = total + v.Money - v.Refund // 减去退款才是真的支出
	}

	// 年度支出汇总完毕
	total = utils.NumberToStr(total)
	data.TopCard.TotalPayment = total

	// 3，借入汇总，不按年份，算总数
	var oweData []paylog.OweLog
	if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
		Where("done = ?", false). // 仅获取未完结的，即借入的，未全部还清的
		Find(&oweData); err.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "汇总借入金额出错！" + err.Error.Error(),
		})
	}

	// 总数重置为0
	total = float64(0)
	for _, v := range oweData {
		// 计算剩余未还
		remainMoney := v.OweMoney - v.PaybackMoney
		total = total + remainMoney
	}

	// 总借入金额汇总完毕
	total = utils.NumberToStr(total)
	data.TopCard.TotalOwe = total

	// 4，借出汇总，不按年份，算总数
	var lendData []paylog.LendLog
	if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
		Where("done = ?", false). // 仅获取未完结的，即借入的，未全部还清的
		Find(&lendData); err.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "汇总借入金额出错！" + err.Error.Error(),
		})
	}

	// 总数重置为0
	total = float64(0)
	for _, v := range lendData {
		// 计算剩余未还
		remainMoney := v.OweMoney - v.PaybackMoney
		total = total + remainMoney
	}

	// 借入总金额汇总完成
	total = utils.NumberToStr(total)
	data.TopCard.TotalLend = total

	// 5, 汇总本周收入
	var weekIncomeData []paylog.IncomeLog
	if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
		Where("time >= ? AND time <= ?", weekStart, weekEnd).
		Find(&weekIncomeData); err.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "本周收入汇总出错！" + err.Error.Error(),
		})
	}

	total = float64(0)
	for _, v := range weekIncomeData {
		total = total + v.Money
	}

	// 本周收入汇总完成
	total = utils.NumberToStr(total)
	data.ThisWeek.TotalIncome = total

	// 6, 汇总本周支出
	var weekPaymentData []paylog.PayLog
	if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
		Where("time >= ? AND time <= ?", weekStart, weekEnd).
		Find(&weekPaymentData); err.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "汇总本周支出出错！" + err.Error.Error(),
		})
	}

	// 总数重置为0
	total = float64(0)
	for _, v := range weekPaymentData {
		total = total + v.Money
	}

	// 本周支出汇总完毕
	total = utils.NumberToStr(total)
	data.ThisWeek.TotalPayment = total

	// 7, 汇总本月收入
	var monthIncomeData []paylog.IncomeLog
	if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
		Where("time >= ? AND time <= ?", monthStart, monthEnd).
		Find(&monthIncomeData); err.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "本月收入汇总出错！" + err.Error.Error(),
		})
	}

	total = float64(0)
	for _, v := range monthIncomeData {
		total = total + v.Money
	}

	// 本月收入汇总完成
	total = utils.NumberToStr(total)
	data.ThisMonth.TotalIncome = total

	// 8, 汇总本月支出
	var monthPaymentData []paylog.PayLog
	if err := global.DB.Where("user_id = ?", global.AuthUser.UserId).
		Where("time >= ? AND time <= ?", monthStart, monthEnd).
		Find(&monthPaymentData); err.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "汇总本月支出出错！" + err.Error.Error(),
		})
	}

	// 总数重置为0
	total = float64(0)
	for _, v := range monthPaymentData {
		total = total + v.Money
	}

	// 本周支出汇总完毕
	total = utils.NumberToStr(total)
	data.ThisMonth.TotalPayment = total

	return ctx.JSON(fiber.Map{
		"status": "done",
		"data":   data,
	})
}
